﻿using System.Data.SqlTypes;
using System.Linq;
using log4net;
using Microsoft.SqlServer.Types;

namespace Storage.EntityModels
{
    #region DrivingInfo
    
    /// <summary>
    /// This class represents a Driving Info into entieties model.
    /// </summary>
    public partial class DrivingInfo : IPersistable
    {
        #region Private fields: _mapPoint, _logger

        private SqlGeography _mapPoint;

#if LOG
        private static readonly ILog _logger = LogManager.GetLogger(typeof(DrivingInfo));
#endif

        #endregion

        #region Public properties: MapPoint

        /// <summary>
        /// Gets or sets the associated geospatial point.
        /// </summary>
        public SqlGeography MapPoint
        {
            get
            {
                return _mapPoint;
            }
            set
            {
                _mapPoint = value;
                StorageManager.Instance.Entities.AddToCustomUpdates(this);
            }
        }

        #endregion

        #region Partial methods: OnLoaded

        partial void OnLoaded()
        {
            TripLoaDataContext db = StorageManager.Instance.Entities;
            var q = db.DrivingInfo_selectGeoRefDataByPk(StageId, InfoOrdinal);

            _mapPoint = SqlGeography.STPointFromText(new SqlChars(q.First().MapPoint), 4326);
        }

        #endregion

        #region IPersistable Members

        /// <summary>
        /// This function inserts a DrivingInfo entity into DrivingInfos table.
        /// </summary>
        /// <param name="db">The BaseTripLoaDataContext.</param>
        public void OnInsert(BaseTripLoaDataContext db)
        {
            db.DrivingInfo_insertAsBinary(StageId, InfoOrdinal, MapPoint.STAsBinary().Buffer, Info);
#if LOG
            _logger.Debug(string.Format("OnInsert"));
#endif
        }

        /// <summary>
        /// This function updates a DrivingInfo entity into DrivingInfos table.
        /// </summary>
        /// <param name="db">The BaseTripLoaDataContext.</param>
        public void OnUpdate(BaseTripLoaDataContext db)
        {
            db.DrivingInfo_updateAsString(StageId, InfoOrdinal, MapPoint.ToString(), Info);
#if LOG
            _logger.Debug(string.Format("OnUpdate"));
#endif
        }

        #endregion
    } 

    #endregion
}
